<?php
namespace app\admin\controller;

class Category extends Common
{
    private $obj;
    public function _initialize()
    {
        parent::_initialize();
        $this->obj = model('Category');
    }

    public function index()
    {
        $data = $this->obj->getCateTreeByPid();
        $this->assign('data', $data);
        return view();
    }

    public function save_category() {
        $id = input('param.id', 0);
        if (request()->isPost()) {
            /**
             * 组装数据
             */
            $data['name'] = input('post.name', '');
            $data['pid'] = input('post.pid', 0);
            $data['level'] = $this->obj->getCategoryLevel(input('param.pid', 0));

            /**
             * 验证数据
             */
            $validate = validate('Category');
            if(!$validate->check($data)) {
                $this->error($validate->getError());
            }

//            /**
//             * 检查分类名是否存在
//             */
//            $where['id'] = $id > 0 ? ['neq', $id] : ['neq', 0];
//            $where['name'] = $data['name'];
//            $where['delete'] = 0;
//            $where['status'] = 1;
//            $cate = $this->obj->getCategory($where);
//            if ($cate) {
//                $this->error('分类名已存在');
//            }

            /**
             * 保存数据
             */
            $where = $id > 0 ? ['id' => $id] : [];
            $rs = $this->obj->save($data, $where);

            // 清理缓存
            \app\api\service\Base::clear_cache();

            if ($rs) {
                $this->success('保存成功');
            } else {
                $this->error('保存失败');
            }
        } else{
            $ztree = $this->obj->getCateZTree();
            $this->assign('ztree', $ztree);

            $data = [];
            if ($id > 0) {
                $data = $this->obj->get(['id' => $id]);
            }
            $this->assign('data', $data);
            return view();
        }
    }

    /**
     * 修改分类排序
     */
    public function sort() {
        $id = input('param.id');
        $sort = input('param.sort');
        $rs = model('category')->save(['sort' => $sort], ['id' => $id]);
        if ($rs) {
            $this->success('保存成功');
        } else {
            $this->error('保存失败');
        }
    }
}
